package dtu.k12tpm.pbs.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import dtu.k12tpm.pbs.regenerate_objects.UserInfo;
import dtu.k12tpm.pbs.service.WebService;

public class FriendListActivity extends MyActivity implements OnItemClickListener {

	private ArrayList<UserInfo>		items	= new ArrayList<UserInfo>();
	private ListView				lv;
	private ArrayAdapter<UserInfo>	aa;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("My friends Android");
		setContentView(R.layout.friend_list);
		lv = (ListView) findViewById(R.id.List);
		try {
			items = WebService.getListUsername(LoginActivity.getUserID());
			if (!items.isEmpty()) {
				((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
			} else {
				((TextView) findViewById(R.id.tvMessageEmptyList)).setText("Don't have any friends");
			}
			aa = new ArrayAdapter<UserInfo>(this, R.layout.item_username_info, items) {

				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_username_info, null);
					}
					UserInfo info = items.get(position);

					if (info != null) {
						TextView display_name = (TextView) v.findViewById(R.id.tvTopLeftInfo);
						TextView username = (TextView) v.findViewById(R.id.tvBottomRightInfo);
						CheckBox cb = (CheckBox) v.findViewById(R.id.chkSelectContact);
						cb.setChecked(info.isChecked());
						display_name.setText(info.getDisplayname());
						username.setText(info.getUsername());
					}
					return v;
				}
			};
			lv.setAdapter(aa);
			lv.setOnItemClickListener(this);
		} catch (Exception e) {
			showMessageDialog("Exception", e.getMessage());
		}
	}

	private void addUserDialog() {
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View content = vi.inflate(R.layout.add_friend, null);
		
		final EditText inputBoxUsername = (EditText)content.findViewById(R.id.txtUsername);
		final EditText inputBoxDisplayName = (EditText)content.findViewById(R.id.txtDisplayname);

		if (!items.isEmpty()) {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("Don't have any items");
		}
		new AlertDialog.Builder(this).setView(content).setTitle("Add friend").setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				String username = inputBoxUsername.getText().toString().trim();
				String display_name = inputBoxDisplayName.getText().toString().trim();
				if (username.equals("")) {
					showToast("Please enter username");
					return;
				} else {
					try {
						WebService.Result result = WebService.addUser(LoginActivity.getUserID(), username, display_name);
						if (result == WebService.Result.SUCCESSED) {
							FriendListActivity.this.items = WebService.getListUsername(LoginActivity.getUserID());
							showToast("Added '"+(display_name.trim().equals("")?username:display_name.trim())+"'");
							FriendListActivity.this.onCreate(FriendListActivity.this.getIntent().getExtras());
						} else if (result == WebService.Result.FAILED) {
							showToast("Add Failed!");
						} else {
							showToast("Exception when attempting query to database");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}

	private void editFriendDialog(final UserInfo info) {
		final LinearLayout ll = new LinearLayout(this);
		final EditText inputBoxDisplayName = new EditText(this);

		inputBoxDisplayName.setText(info.getDisplayname());

		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(5, 5, 5, 5);
		ll.addView(inputBoxDisplayName, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		inputBoxDisplayName.setSingleLine(true);

		inputBoxDisplayName.setHint("Display name");
		new AlertDialog.Builder(this).setView(ll).setTitle("Edit " + info.getUsername()).setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				String display_name = inputBoxDisplayName.getText().toString().trim();
				try {
					WebService.Result result = WebService.updateUser(LoginActivity.getUserID(), display_name, info.getId());
					if (result == WebService.Result.EXCEPTION) {
						showToast("Exception when attempting update");
					} else if (result == WebService.Result.FAILED) {
						showToast("Update Failed!");
					} else {
						info.setDisplayName(display_name);
						aa.notifyDataSetChanged();
						showToast("Updated '"+display_name.trim()+"'");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}

	public void addUsernameClick(View v) {
		addUserDialog();
	}

	public void removeUsernameClick(View v) {
		if (items.isEmpty()) {
			showToast("Don't have any friends");
			return;
		}
		if (numberOfItemsSelected == 0) {
			showToast("Please choose any items");
			return;
		}

		showConfirmDialog("Remove", "Do you want to remove?", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				int removed = 0;
				for (int i = 0; i < items.size(); i++) {
					if (items.get(i).isChecked()) {
						try {
							int count = WebService.removeUser(LoginActivity.getUserID(), items.get(i).getUsername());
							if (count > 0) {
								removed++;
								items.remove(i);
								i -= count;
								numberOfItemsSelected -= count;
								aa.notifyDataSetChanged();
							} else {
							}
						} catch (Exception e) {
							showMessageDialog("Exception", "UMA-165: " + e.getMessage());
						}
					}
				}
				showToast("Removed " + removed + (removed > 1 ? " elements" : "element"));
				if (!items.isEmpty()) {
					((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
				} else {
					((TextView) findViewById(R.id.tvMessageEmptyList)).setText("Don't have any items");
				}
			}
		});
	}

	private int	numberOfItemsSelected	= 0;

	public void radioButtonClick(View v) {
		CheckBox cb = (CheckBox) v;
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(cb.isChecked());
		numberOfItemsSelected += cb.isChecked() ? 1 : -1;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		editFriendDialog(items.get(arg2));
	}
}
